<template>
	<view class="content" >
		<view class="answer-content">
			<view class="answer-title"><text>{{question}}</text></view>
			<view class="result-tips">您本次测试的结果为</view>
			<image class="result-img" :src="resultImg" mode="widthFix" alt="" />
		</view>
		<view class="program-tips">--本小程序仅供娱乐--</view>
		<view class="view-result" @click="savePoster">
			<text v-if="this.use_RewardedVideoAd">看广告保存测试结果</text>
			<text v-else>点击保存测试结果</text>
		</view>
		
		<view class="list">
			<view class="scroll-head">
				<image src="../../static/ic-good.png" mode="widthFix"></image>
				<text>更多推荐测试</text>
			</view>
			<view class="list-ul">
				<Item v-for="item in allList" :key="item.topic_id" :item="item" />
			</view>
			<view class="btn-loadmore" @click="loadMoreAction" v-if="!loadOver">查看更多</view>
			<view class="loading-tips" v-else>没有更多数据</view>
		</view>
		
		<view :class="['auth-pu', authPanelVisible ? 'active' : '']">
			<view class="auth-pu-content">
				<view class="auth-pu-text">
					<text>保存图片需要授权相册，请允许授权</text>
				</view>
				<!-- #ifdef MP-QQ||MP-WEIXIN -->
				<button class="auth-pu-confirm" open-type="openSetting" @opensetting="openSettingAction">
					<text>确定</text>
				</button>
				<!-- #endif -->
				<!-- #ifdef MP-TOUTIAO -->
				<button class="auth-pu-confirm" @click="openSavePhotosAlbum">
					<text>确定</text>
				</button>
				<!-- #endif -->
			</view>
		</view>
	</view>
</template>

<script>
	import config from '../../src/config/api.config.js';
	import utils from '../../src/utils/utils.js';
	import userCheck from '../../src/utils/user.js';
	import request from '../../src/utils/request.js';
	import ActionSheet from '../../src/components/actionSheet.vue';
	import Item from '../index/item.vue';

	
	// 在页面中定义激励视频广告
	let videoAd = null
	
	// #ifdef MP-TOUTIAO
	const info = tt.getSystemInfoSync();
	if (info.appName.toUpperCase() === 'DOUYIN') {
		videoAd = tt.createRewardedVideoAd({
			adUnitId: '14goeia432f2l3ie3e'
		});
	}
	// #endif
	
	export default {
		data() {
			return {
				id: '', // 测评id
				bodyBackgroundColor: '', // 页面背景颜色
				resultImg: '', // 测评结果图片地址
				recomList: [], // 推荐列表
				question: '', // 题目
				isLoading: false, // 是否加载中
				loadOver: false, // 是否加载完成
				page: 1, // 页码
				authPanelVisible: false, // 相册授权面板可视化
				actionSheetVisible: false, // 长按弹窗可视化
				openid:'',
				showTtVideo:1,//1-不显示 2-显示
				preImg:'',
				use_RewardedVideoAd:true,
				tt_share_template_id:'',//头条分享id
				shareType:0,
				allList: [], // 全部
			}
		},
		
		onLoad(options) {
			const that = this;
			console.log('kylekylekylekyle')
			console.log(options);
			this.bodyBackgroundColor = decodeURIComponent(options.color);
			this.resultImg = decodeURIComponent(options.src);
			this.id = options.id;
			this.openid = options.openid;
			this.question = options.question;
			this.showTtVideo = options.showTtVideo;
			this.preImg = options.preImg;
			this.tt_share_template_id = options.tt_share_template_id;
			this.shareType = options.shareType;
			console.log(this.shareType)
			console.log('kylekylekylekyle')
			this.getRecomList();
			// #ifdef MP-WEIXIN
			// 微信小程序设置分享配置
			wx.showShareMenu({
				// shareTicket 是获取转发目标群信息的票据，只有拥有 shareTicket 才能拿到群信息，用户每次转发都会生成对应唯一的shareTicket 。
				withShareTicket: true,
			});
			
			
			// 在页面onLoad回调事件中创建激励视频广告实例
			if (wx.createRewardedVideoAd) {
				videoAd = wx.createRewardedVideoAd({
					adUnitId: 'adunit-acbaabb9b2675275'
				})
				videoAd.onLoad(() => {})
				videoAd.onError((err) => {})
				videoAd.onClose((res) => {
					console.log('videoAd onClose', res)
					if (res.isEnded) {
						console.log('观看完成')
						that.downloadResutlImg();
					} else {
						console.log('半途而废')
			
					}
				})
			}
			// #endif
			
			// #ifdef MP-TOUTIAO
			//判断当前设备，激励广告只能在抖音高版本里使用
			
			if (info.appName.toUpperCase() !== 'DOUYIN') {
				this.use_RewardedVideoAd = false
			} else {
				//可以看激励广告
				try {
					if (videoAd.closeFunc) {
						videoAd.offClose(videoAd.closeFunc);
					}
				} catch (e) {
					console.warn("--------------videoAd.offClose error:");
					console.error(e);
					that.downloadResutlImg();
				}
				videoAd.closeFunc = function(res) {
					// 用户点击了【关闭广告】按钮
					// 小于基础库版本，res 是一个 undefined
					console.warn("播放完毕", res);
					console.log("当前页面id：" + that.id)
					if (res && res.isEnded || res === undefined) { // 正常播放结束，可以下发游戏奖励
						console.log('可以下发奖励了')
						// 给予奖励
						console.log('观看完成')
						that.downloadResutlImg();
						
					}
				};
				videoAd.onClose(videoAd.closeFunc);
			}
			// #endif
		},
		
		methods: {
			// #ifdef MP-TOUTIAO
			openSavePhotosAlbum() {
				const that = this;
				tt.openSetting({
					success(r){
						tt.authorize({
							scope: "scope.album",
							success(r) {
								that.authPanelVisible = false;
							}
						})
					}
				})
			},
			// #endif
			// 获取推荐列表
			async getRecomList() {
				this.isLoading = true;
				const r = await request({
					url: `${config.API}api/topic/list`,
					data: {
						page: this.page
					}
				});
				this.isLoading = false;
				if (r.error_code === 0) {
					// this.recomList = [...this.recomList, ...r.data.topicList.data];
					this.allList = [...this.allList, ...r.data.topicList.data];
					if (r.data.topicList.current_page >= r.data.topicList.last_page) {
						this.loadOver = true;
					}
				}
			},
			// 保存图片
			savePoster() {
				// #ifdef H5 || MP-ALIPAY
				return uni.showToast({
					title: '暂不支持保存',
					icon: 'none',
					duration: 2000
				})
				// #endif
				let that = this
				console.log(that.use_RewardedVideoAd)
				if(that.use_RewardedVideoAd && that.shareType == 2){
					// uni.showModal({
					//     title: "温馨提示",
					//     content: "观看广告完可保存至相册，不可中断！",
					//     success: function (res) {
					//         if (res.confirm) {
					//             console.log('用户点击确定');
					// 			//看广告出视屏
					// 			that.showVideo()
					//         } else if (res.cancel) {
					//             console.log('用户点击取消');
					//         }
					//     }
					// });
					that.showVideo()
				}else{
					that.downloadResutlImg()
				}
				
			},
			downloadResutlImg(){
				let that = this
				uni.downloadFile({
					url: that.resultImg,
					success(downloadFileData) {
						uni.saveImageToPhotosAlbum({
							filePath: downloadFileData.tempFilePath,
							success(saveResult) {
								uni.showToast({
									title: '保存成功',
									icon: 'none'
								});
							},
							fail: failRes => {
								console.log(failRes);
								// 如果保存失败，是否没有授权
								if (failRes.errMsg === 'saveImageToPhotosAlbum:fail auth deny' || failRes.errMsg ===
									'saveImageToPhotosAlbum:fail authorize deny') {
									that.authPanelVisible = true;
								}
							},
							complete: () => {
								that.actionSheetVisible = false;
							}
						});
					}
				})
			},
			// 分享说说
			shareWithQQZone() {
				// #ifdef MP-QQ
				return qq.openQzonePublish({
					text: '',
					media: [{
						type: 'photo',
						path: this.resultImg
					}]
				});
				// #endif
				uni.showToast({
					title: '暂不支持分享到QQ空间',
					icon: 'none'
				})
			},
			// 打开授权设置回调
			openSettingAction(r) {
				this.authPanelVisible = false;
			},
			/**
			 * 首页
			 * @param {number} id 测评id  
			 */
			goToIndex(id) {
				uni.redirectTo({
					url: `/pages/index/index?id=${id}`
				});
			},
			// #ifdef MP-QQ
			//qq端-查看激励视频
			showVideo() {
				const that = this;
				let videoAd = qq.createRewardedVideoAd({
					adUnitId: '6f3056a035c51f7bf29ae9c622c3d0fa'
				})
				videoAd.onClose(function(res) {
					console.log('videoAd onClose', res)
					if (res.isEnded) {
						console.log('观看完成')
						
						that.downloadResutlImg();
					} else {
						console.log('半途而废')
			
					}
				})
				videoAd.load().then(() => {
					console.log('激励视频加载成功');
					videoAd.show().then(() => {
						console.log('激励视频 广告显示成功')
					}).catch(err => {
						console.log('激励视频 广告显示失败')
						that.downloadResutlImg();
					})
				}).catch(err => {
					console.log('激励视频加载失败');
					that.downloadResutlImg();
				})
			},
			// #endif
			
			// #ifdef MP-WEIXIN
			showVideo() {
				const that = this;
				// 用户触发广告后，显示激励视频广告
				if (videoAd) {
					videoAd.show().catch(() => {
						// 失败重试
						videoAd.load()
							.then(() => videoAd.show())
							.catch(err => {
								console.log('激励视频 广告显示失败')
								that.downloadResutlImg();
							})
					})
				} else { //每天看激励广告的次数有限，当没调用起广告时直接显示结果
					that.downloadResutlImg();
				}
			},
			// #endif
			
			// #ifdef MP-TOUTIAO
			//头条端-查看激励视频
			showVideo() {
				const that = this;
				console.log('显示广告');
				videoAd.show().catch(() => { // 失败重试
					videoAd
						.load()
						.then(() => videoAd.show())
						.catch(err => {
							console.log('激励视频 广告显示失败')
							that.downloadResutlImg();
						})
				});
			},
			// #endif
		},
		onReachBottom(r) {
			if (this.loadOver || this.isLoading) return;
			this.page++;
			this.getRecomList();
		},
		// 分享操作
		onShareAppMessage(r) {
			//由于官方声明不会分享回调告知开发者，因此无法针对回调做触发，只能直接显示
			let _path = '/pages/index/index?parentOpenid=' + this.openid + '&id=' + this.id  + '&title=' + this.question;
			console.log(_path)
			// #ifdef MP-QQ||MP-WEIXIN
			return {
				title: this.shareMsg.title,
				imageUrl: this.resultStep === 1 ? this.poster.src : this.preImg,
				path: _path, //带上当前用户的openid，分销绑定关系
			}
			// #endif
			// #ifdef MP-TOUTIAO
			if(this.tt_share_template_id != ''){
				return {
					templateId:this.tt_share_template_id,
					path: _path, //带上当前用户的openid，分销绑定关系
				}
			}else{
				return {
					title: '有趣的测试玩一玩',
					imageUrl: this.resultStep === 1 ? this.poster.src : this.preImg,
					path: _path, //带上当前用户的openid，分销绑定关系
				}
			}
			// #endif
		},
		components: {
			ActionSheet,
			Item
		}
	}
</script>

<style lang="scss" scoped>
	$color9: #999;
	$white: #fff;
	$black: #333;
	$blue: #5b78ff;
	$gray: #eee;
	.content {
		min-height: 100vh;
		box-sizing: border-box;
		padding-bottom: 40rpx;
		overflow: hidden;
	}
	.answer-content {
		margin: 40rpx 40rpx 0;
		background-color: white;
		border-radius: 16rpx;
		box-sizing: border-box;
		padding: 40rpx 30rpx;
	
		.answer-title {
			font-size: 56rpx;
			font-weight: bold;
			text-align: center;
			padding: 20rpx 0;
			border-bottom: 1rpx solid #eee;
		}
		.result-tips {
			font-size: 32rpx;
			padding: 30rpx 0;
			text-align: center;
		}
		.result-img {
			width: 100%;
		}
	}
	.view-result {
		margin: 40rpx;
		text-align: center;
		color: #fff;
		background-color: $blue;
		border-radius: 16rpx;
		padding: 30rpx 0;
	}
	.auth-pu {
		position: fixed;
		top: 0;
		left: 0;
		bottom: 0;
		right: 0;
		z-index: 3;
		background-color: rgba(0, 0, 0, .6);
		justify-content: center;
		align-items: center;
		animation: maskShow 300ms;
		display: none;
	
		&.active {
			display: flex;
		}
	
		.auth-pu-content {
			background-color: white;
			width: 80%;
	
			.auth-pu-text {
				padding: 60rpx 40rpx;
				text-align: center;
	
				text {
					font-size: 32rpx;
					color: $black;
				}
			}
	
			.auth-pu-confirm {
				border-top: 1px solid $gray;
				height: 100rpx;
				line-height: 100rpx;
				text-align: center;
	
				text {
					font-size: 32rpx;
					color: $blue;
				}
			}
		}
	}
	
	.actionsheet-item {
		background-color: #fff;
		border-radius: 10rpx;
		height: 100rpx;
		line-height: 100rpx;
		text-align: center;
		margin-bottom: 2px;
		overflow: hidden;
		box-sizing: content-box;
	
		button {
			height: 100%;
			line-height: 100rpx;
			padding: 0;
			box-sizing: border-box;
		}
	
		text {
			font-size: 32rpx;
			color: #333;
		}
	}
	.custom-share-button{
		
		img{
			width: 32rpx;
			height: 32rpx;
			vertical-align: middle;
			margin-top: -2px;
			margin-right: 2px;
		}
		background-color: #007AFF;
		border-radius: 30px;
		border-top-right-radius: 0px;
		border-bottom-right-radius: 0px;
		line-height: 40rpx;
		text-align: right;
		padding: 6rpx 18rpx 6rpx 28rpx;
		font-size: 24rpx;
		background-color: #fff;
		position: fixed;
	    right: 0;
	    bottom: 90%;
	    z-index:2000;
	}
	.custom-share-button::after{
		border: 0px solid red;
	}
	
	.custom-share-button2{
		background-color: #007AFF;
		border-radius: 30px;
		border-top-right-radius: 0px;
		border-bottom-right-radius: 0px;
		line-height: 40rpx;
		text-align: right;
		padding: 6rpx 18rpx 6rpx 28rpx;
		font-size: 24rpx;
		background-color: #fff;
		position: fixed;
	    right: 0;
	    bottom: 84%;
	    z-index:2000;
	}
	.custom-share-button2::after{
		border: 0px solid red;
	}
	.program-tips {
		text-align: center;
		font-size: 24rpx;
		color: gray;
		padding: 30rpx 0 0;
	}
	
	//更多测试样式
	.scroll-head {
		display: flex;
		align-items: center;
		padding: 36rpx 30rpx;
		image {
			display: block;
			width: 28rpx;
			height: 28rpx;
			margin-right: 10rpx;
		}
		text {
			font-size: 36rpx;
			font-weight: bold;
			color: #333;
		}
	}
	.list {
		.scroll-head {
			border-bottom: 1px solid #f1f1f1;
		}
	}
	
	.loading-tips {
		font-size: 28rpx;
		color: $color9;
		padding: 20rpx 0;
		text-align: center;
		margin-bottom: 20rpx;
	}
	
</style>
